package com.gao.demo02;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 生产者消费者
 * 线程之间的通信问题
 * 线程交替执行 A B 操作同一个变量 num = 0
 * JUC 版本
 * A num + 1
 * B num - 1
 */
public class demo02 {
    public static void main(String[] args) {
        ResourceJUC resourceJUC = new ResourceJUC();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    resourceJUC.increase();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    resourceJUC.decrease();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    resourceJUC.increase();
                } catch (InterruptedException e) {

                }
            }
        },"C").start();

        new Thread(()->{
            for (int i = 0; i < 10; i++) {
                try {
                    resourceJUC.decrease();
                } catch (InterruptedException e) {

                }
            }
        },"D").start();

    }
}

//判断等待 -> 业务 -> 通知 生产者消费者模式
class ResourceJUC {
    private int number = 0;

    Lock lock = new ReentrantLock();
    Condition condition = lock.newCondition();
//    condition.await();            等待
//    condition.signalALl();        唤醒全部

    public void increase() throws InterruptedException {

        lock.lock();

        try {
            while (number != 0) {
    //            等待 JUC
                condition.await();
            }
//        业务
            number++;
            System.out.println(Thread.currentThread().getName() + " -> " + number);
//        通知其他线程，我+1完毕 JUC
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    public void decrease() throws InterruptedException {

        lock.lock();

        try {
            while (number == 0) {
    //            等待 JUC
                condition.await();
            }
//        业务
            number--;
            System.out.println(Thread.currentThread().getName() + " -> " + number);
//        通知其他线程，我-1完毕 JUC
            condition.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
}
